package ltd.jdsoft.cute.spring.web.response;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import ltd.jdsoft.cute.api.StatusCodeEnum;
import ltd.jdsoft.cute.api.http.Meta;
import ltd.jdsoft.cute.api.http.RestResponse;

/**
 * 采用builder模式来构造返回信息
 * 
 * @author zhengzhq
 *
 */
public class ResponseBuilder {

  private static final String errorHeader = "x-error";
  private Meta meta = null;
  private Map<String, Object> dataMap = null;

  public static ResponseBuilder newBuilder() {
    return new ResponseBuilder();
  }

  public static ResponseBuilder newBuilder(HttpServletResponse response) {
    response.setHeader(errorHeader, "true");
    return new ResponseBuilder();
  }

  public ResponseBuilder setMeta(StatusCodeEnum status) {
    meta = new Meta(status);
    return this;
  }

  public ResponseBuilder setMeta(int code, String message) {
    meta = new Meta(code, message);
    return this;
  }

  public ResponseBuilder setData(Map<String, Object> dataMap) {
    this.dataMap = dataMap;
    return this;
  }

  public RestResponse build() {
    // 如果有数据代表肯定是成功，也就是meta.code=200
    if (this.dataMap != null) {
      return new RestResponse(dataMap);
    }
    return new RestResponse(meta);
  }
}
